package com.wpg.demo.spring.xml;

import com.wpg.demo.spring.xml.addressbook.domain.AddressBook;
import com.wpg.demo.spring.xml.addressbook.service.AddressBookService;
import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

import java.util.List;

/**
 * @author ChangWei Li
 * @version 2017-02-20 09:51
 */
public class Application {

    public enum  ConfigType {
        GROOVY("groovy"), XML("xml");

        private final String suffix;

        ConfigType(String suffix) {
            this.suffix = suffix;
        }

        public static ConfigType determinTypeWithSuffix(String configName) {
            String suffix = configName.substring(configName.indexOf(".") + 1);

            switch (suffix) {
                case "groovy":
                    return GROOVY;
                case "xml":
                    return XML;
                default:
                    return XML;
            }
        }
    }

    public static List<AddressBook> directLoad(String ...configNames) {
        ApplicationContext context = new ClassPathXmlApplicationContext(configNames);

        AddressBookService bookService = context.getBean("addressBookService", AddressBookService.class);

        return bookService.getList();
    }

    public static List<AddressBook> indirectLoad(String ...configNames) {
        GenericApplicationContext context = new GenericApplicationContext();
        BeanDefinitionReader beanDefinitionReader;

        switch (ConfigType.determinTypeWithSuffix(configNames[0])) {
            case GROOVY: {
                beanDefinitionReader = new GroovyBeanDefinitionReader(context);
                break;
            }
            case XML: {
                beanDefinitionReader = new XmlBeanDefinitionReader(context);
                break;
            }
            default: {
                beanDefinitionReader = new XmlBeanDefinitionReader(context);
            }
        }

        beanDefinitionReader.loadBeanDefinitions(configNames);

        context.refresh();

        AddressBookService bookService = context.getBean("addressBookService", AddressBookService.class);

        return bookService.getList();
    }

}
